import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css';

// 微信公众号的样式配置
const wechatStyles = {
  h1: 'font-size: 24px; font-weight: bold; margin: 14px 0; color: #1a1a1a; line-height: 1.4;',
  h2: 'font-size: 20px; font-weight: bold; margin: 12px 0; color: #1a1a1a; line-height: 1.4;',
  h3: 'font-size: 18px; font-weight: bold; margin: 10px 0; color: #1a1a1a; line-height: 1.4;',
  h4: 'font-size: 16px; font-weight: bold; margin: 8px 0; color: #1a1a1a; line-height: 1.4;',
  blockquote: 'padding: 15px; margin: 10px 0; border-left: 4px solid #258fb8; background: #f5f5f5; color: #666; font-size: 14px;',
  code: 'background-color: rgba(27,31,35,.05); border-radius: 3px; padding: 3px 5px; color: #24292e; font-family: "Operator Mono", Consolas, Monaco, Menlo, monospace; font-size: 85%;',
  pre: 'background-color: #282c34; padding: 16px; overflow: auto; line-height: 1.45; border-radius: 6px; margin: 10px 0; font-size: 14px;',
  p: 'margin: 1.5em 0; color: #2f2f2f; font-size: 15px; line-height: 2; letter-spacing: 0.05em;',
  list: 'margin: 10px 0; padding-left: 20px; color: #595959; font-size: 15px; line-height: 2;',
  link: 'color: #576b95; text-decoration: none; border-bottom: 1px solid #d1e9ff;',
  image: 'max-width: 100%; margin: 10px auto; display: block; border-radius: 4px;',
  table: 'border-collapse: collapse; margin: 15px 0; width: 100%;',
  th: 'border: 1px solid #dfe2e5; padding: 10px; background-color: #f6f8fa; font-weight: bold;',
  td: 'border: 1px solid #dfe2e5; padding: 10px;',
};

class WechatFormatter {
  private md: MarkdownIt;

  constructor() {
    this.md = new MarkdownIt({
      html: true,
      linkify: true,
      typographer: true,
      highlight: (str, lang) => {
        if (lang && hljs.getLanguage(lang)) {
          try {
            const highlighted = hljs.highlight(str, {
              language: lang,
              ignoreIllegals: true
            }).value;
            
            // 添加行号
            const lines = highlighted.split('\n');
            const numberedLines = lines.map((line, i) => {
              const lineNumber = `<span class="line-number">${i + 1}</span>`;
              return `<div class="line">${lineNumber}${line}</div>`;
            }).join('');

            return `<div class="code-block-wrapper">${numberedLines}</div>`;
          } catch (e) {
            console.error('Error highlighting code:', e);
          }
        }
        return '<pre><code>' + this.md.utils.escapeHtml(str) + '</code></pre>';
      }
    });

    this.setupMarkdownIt();
  }

  private setupMarkdownIt() {
    // 修改渲染规则以添加微信样式
    const defaultRender = this.md.renderer.rules.link_open || function(tokens, idx, options, env, self) {
      return self.renderToken(tokens, idx, options);
    };

    this.md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
      const token = tokens[idx];
      const href = token.attrGet('href');
      
      // 只允许微信域名的链接
      if (href && !href.startsWith('https://mp.weixin.qq.com')) {
        token.attrSet('href', '#');
      }
      
      token.attrSet('style', wechatStyles.link);
      return defaultRender(tokens, idx, options, env, self);
    };

    // 添加图片样式
    const defaultImageRender = this.md.renderer.rules.image || function(tokens, idx, options, env, self) {
      return self.renderToken(tokens, idx, options);
    };

    this.md.renderer.rules.image = (tokens, idx, options, env, self) => {
      const token = tokens[idx];
      token.attrSet('style', wechatStyles.image);
      return defaultImageRender(tokens, idx, options, env, self);
    };

    // 添加标题样式
    ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].forEach(level => {
      const tag = `${level}_open`;
      const defaultHeadingRender = this.md.renderer.rules[tag] || function(tokens, idx, options, env, self) {
        return self.renderToken(tokens, idx, options);
      };

      this.md.renderer.rules[tag] = (tokens, idx, options, env, self) => {
        const token = tokens[idx];
        token.attrSet('style', wechatStyles[level as keyof typeof wechatStyles] || '');
        return defaultHeadingRender(tokens, idx, options, env, self);
      };
    });

    // 添加引用块样式
    const defaultBlockquoteRender = this.md.renderer.rules.blockquote_open || function(tokens, idx, options, env, self) {
      return self.renderToken(tokens, idx, options);
    };

    this.md.renderer.rules.blockquote_open = (tokens, idx, options, env, self) => {
      const token = tokens[idx];
      token.attrSet('style', wechatStyles.blockquote);
      return defaultBlockquoteRender(tokens, idx, options, env, self);
    };

    // 修改代码块样式
    this.md.renderer.rules.fence = (tokens, idx) => {
      const token = tokens[idx];
      const lang = token.info.trim();
      const content = token.content;
      
      let code = '';
      if (lang && hljs.getLanguage(lang)) {
        try {
          const highlighted = hljs.highlight(content, {
            language: lang,
            ignoreIllegals: true
          }).value;
          code = highlighted;
        } catch (e) {
          code = this.md.utils.escapeHtml(content);
        }
      } else {
        code = this.md.utils.escapeHtml(content);
      }

      return `
        <div class="code-block" style="${wechatStyles.pre}">
          <div class="code-header">
            <span class="code-lang">${lang || 'text'}</span>
          </div>
          <pre><code class="hljs language-${lang}">${code}</code></pre>
        </div>
      `;
    };
  }

  format(markdown: string): string {
    return this.md.render(markdown);
  }
}

export const wechatFormatter = new WechatFormatter();
